package com.shooter.utils;

import com.shooter.server.ServiceApi;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Created by BLACK on 2018/3/28.
 */
public class FileUtil {
    //刪除文件操作
    public static boolean deleteFile(String path, String fileName) {
        return deleteFile(path + fileName);
    }

    public static boolean deleteFile(String fullPath) {
        File file = new File(fullPath);
        if (!file.exists()) {
            PrintUtil.printMsg(ServiceApi.TEXT_00001);
        }
        return file.delete();
    }

    //获取文件 转为文本
    public static String openFileText(String path, String fileName) {
        String text = new String(openFileByte(path, fileName));
        return text;
    }

    private static FileInputStream openFile(String path, String fileName) {
        return openFile(path + fileName);
    }

    //获取文件流
    private static FileInputStream openFile(String fullPath) {
        File file = new File(fullPath);
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
        } catch (IOException e) {
            PrintUtil.printError(e);
        }
        return fis;
    }

    //创建文件夹
    public static void createFilePath(String path) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    public static byte[] openFileByte(String path, String fileName) {
        return openFileByte(path + fileName);
    }

    //获取文件byte数据
    public static byte[] openFileByte(String fullPath) {
        FileInputStream fis = openFile(fullPath);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int len;
        try {
            while ((len = fis.read(bytes)) != -1) {
                baos.write(bytes, 0, len);
                baos.flush();
            }
        } catch (IOException e) {
            PrintUtil.printError(e);
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                PrintUtil.printError(e);
            }

        }
        return baos.toByteArray();
    }
}
